# coding:utf-8
"""
处理接口请求
"""
import ia_configure
import ia_http
import ia_json
import time
import requests
import json
# import ia_log
import ia_pickle
import ia_wx
import ia_sql
import ia_token
from ia_log import Logger
from datetime import datetime, timedelta
auth_jianquan = ia_token.get_auth(1)
auth_vice = ia_token.get_auth(0)
auth_no = ia_token.get_auth_no()
interface_url = ia_configure.interface_dir
logger_e = Logger().getlog()
host = ia_configure.url_ym
phttp=ia_http.py_http()
pjson = ia_json.py_json()
store = {}
def judge(data):
    code = data[4]
    if code == 200:
        success_result(data)
    else:
        fail_result(data)
def logger_error(interface,case,info):
    logger_e.error("接口'%s'"%interface+' - case:'+case+' - 错误信息:%s'%info)
def logger(interface, case, info):
    logger_error(interface, case, info)
    try:
        if interface[0:4] == 'http':
            text = 'h5'
        else:
            text = interface[1:].split("/")[0].split('?')[0]
        iter_now = datetime.now()
        period_next = timedelta(days=0, hours=0, minutes=ia_configure.fail_mins, seconds=0)
        iter_time = iter_now + period_next
        chnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S')
        ia_sql.update_time(text,str(chnext_time))
    except:
        pass
    if ia_configure.is_send == 1:
        if interface[0:4] == 'http':
            send_weixin_message = '接口:%s'%(interface) + '   case:%s'%case + '  错误信息:%s'%info
            sendweixin(send_weixin_message)
        else:
            send_weixin_message = '接口:%s%s'%(ia_configure.url_ym,interface) + '   case:%s'%case + '  错误信息:%s'%info
            sendweixin(send_weixin_message)
def sendweixin(text):
    value = ia_wx.weixin_msg()
    value.wx_Msg_txt(value.surl,'toparty',ia_configure.id_txl_qa,ia_configure.id_app_jiekou,text)
def send_json(res):
    up_data = json.dumps(res)
    requests.post(interface_url,up_data)
def success_result(data):
    result = {'host':host,'interface':data[0],'result':1,'module':data[1],'casename':data[2],'time':data[3],'code':data[4],'data':data[5],'message':data[6],'request_id':data[7],'request_time':data[8],'response_time':data[9]}
    send_json(result)
def h5_success_result(data):
    result = {'host':'H5页面','interface':data[0],'result':1,'module':data[1],'casename':data[2],'time':data[3],'code':data[4],'data':data[5],'message':data[6],'request_id':data[7],'request_time':data[8],'response_time':data[9]}
    send_json(result)
def h5_fail_result(data):
    result = {'host':'H5页面','interface':data[0],'result':0,'module':data[1],'casename':data[2],'time':data[3],'code':data[4],'data':data[5],'message':data[6],'request_id':data[7],'request_time':data[8],'response_time':data[9]}
    send_json(result)
def fail_result(data):
    result = {'host':host,'interface':data[0],'result':0,'module':data[1],'casename':data[2],'time':data[3],'code':data[4],'data':data[5],'message':data[6],'request_id':data[7],'request_time':data[8],'response_time':data[9]}
    send_json(result)
def res_page(test_list):
    try:
        account = test_list[0][0]
        method = test_list[0][1]
        is_auth = test_list[0][2]
        is_getdata = test_list[0][3]
        case_name = test_list[0][4]
        dj_data = test_list[1]
        tt_interface = test_list[0][5][0]
        tt_model = test_list[0][5][1]
        tt_case = test_list[0][5][2]
        ISOTIMEFORMAT = '%Y-%m-%d %X'
        timestamp = time.strftime( ISOTIMEFORMAT, time.localtime() )
        # timestamp = time.time()
        model = tt_interface[1:].split("/")[0].split('?')[0]
        if model in ['goods','sums','pay']:
            model = 'pay'
    except:
        logger('接口','case','用例参数不完整')
        return False
    send_data = []
    try:
        if method == 'get':
            i_data = ''
        elif method == 'post':
            i_data = test_list[2][0]
        else:
            logger(tt_interface,tt_case,'get/post参数错误')
            return False
    except:
        logger(tt_interface,tt_case,'post方法没有添加post数据')
        return False
    if is_auth == 1:
        if account == 1:
            auth = eval(auth_jianquan)
        else:
            auth = eval(auth_vice)
    else:
        logger(tt_interface,tt_case,'是否鉴权参数错误')
        return False
    #URL添加参数
    t = []
    n = []
    try:
        if is_getdata == 0:
            getdata = ''
        elif is_getdata == 1:
            getdata = test_list[0][6]
            for in_data in getdata:
                text = ia_pickle.load(in_data[0],model)
                if in_data[1] == '':
                    for te in in_data[2]:
                        valn = pjson.json_getvalue(pjson.json_load(text),te)
                        t.append(valn)
                else:
                    val=pjson.json_getvalue(pjson.json_load(text),in_data[1])
                    for (k,v) in val.items():
                        n.append(k)
                    for (k,v) in val.items():
                        for values in in_data[2]:
                            if values in n:
                                if k == values:
                                    t.append(v)
                            else:
                                fail_result(send_data)
                                logger(tt_interface,tt_case,'返回数据没有该校验参数')
                                break
        else:
            logger(tt_interface,tt_case,'用例返回数据参数错误')
            return False
    except:
        logger_error(tt_interface,tt_case,'接口参数未获取到')
        return False
    if is_getdata == 1:
        if len(t) == 0:
            logger(tt_interface,tt_case,'用例返回数据参数错误')
            return False
        elif len(t) == 1:
            tt_interface = tt_interface%t[0]
        elif len(t) == 2:
            tt_interface = tt_interface%(t[1],t[0])
        elif len(t) == 3:
            tt_interface = tt_interface%(t[2],t[1],t[0])
    tt_interface = str(tt_interface)
    if model == 'pay':
        page=phttp.http_read(ia_configure.pay_url+tt_interface,auth,ia_configure.t_http,i_data)
    else:
        page=phttp.http_read(ia_configure.url_ym+tt_interface,auth,ia_configure.t_http,i_data)
    store[case_name] = page
    ia_pickle.store(store,model)
    send_data.append(tt_interface)
    send_data.append(tt_model)
    send_data.append(tt_case)
    send_data.append(timestamp)
    try:
        code=pjson.json_getvalue(pjson.json_load(page),'code')
        data=pjson.json_getvalue(pjson.json_load(page),'data')
        message=pjson.json_getvalue(pjson.json_load(page),'message')
        # request_id=pjson.json_getvalue(pjson.json_load(page),'request_id')
        # request_time=pjson.json_getvalue(pjson.json_load(page),'request_time')
        # response_time=pjson.json_getvalue(pjson.json_load(page),'response_time')
        send_data.append(code)
        send_data.append(page)
        send_data.append(message)
        if account == 1 :
            send_data.append(ia_configure.user)
            send_data.append(ia_configure.uid)
            send_data.append(ia_configure.name)
        else:
            send_data.append(ia_configure.vice_user)
            send_data.append(ia_configure.vice_uid)
            send_data.append(ia_configure.vice_name)
    except:
        send_data.append('')
        send_data.append('')
        send_data.append('')
        send_data.append('')
        send_data.append('')
        send_data.append('')
        fail_result(send_data)
        logger(ia_configure.pay_url+tt_interface,tt_case,'接口返回数据格式不正确')
        return False
    try:
        for data_pre in dj_data:
            for data in data_pre:
                origin = data[0]
                pos = data[1]
                data_dj = data[2]
                m = []
                if origin == 'self':
                    page = page
                else:
                    page = ia_pickle.load(origin,model)
                #判断获取的值与实现设置的值是否一致
                if pos == '':
                    for (key, values) in data_dj.items():
                        val=pjson.json_getvalue(pjson.json_load(page),key)
                        if type(val) == unicode:
                            val = val.encode('utf-8')
                        if val == values:
                            pass
                        else:
                            fail_result(send_data)
                            logger(tt_interface,tt_case,'参数校验错误,错误参数%s'%str(val))
                            return False
                else:
                    data_pos=pjson.json_getvalue(pjson.json_load(page),pos)
                    for (key, values) in data_dj.items():
                        for (k,v) in data_pos.items():
                            m.append(k)
                        for (k,v) in data_pos.items():
                            if key in m:
                                if k == key:
                                    if type(v) == unicode:
                                        v = v.encode('utf-8')
                                    if v == values:
                                        pass
                                    else:
                                        fail_result(send_data)
                                        logger(tt_interface,tt_case,'参数校验错误')
                                        return False

                            else:
                                fail_result(send_data)
                                logger(tt_interface,tt_case,'返回数据没有该校验参数')
                                return False
        if ia_configure.is_success == 1:

            success_result(send_data)
    except:
        fail_result(send_data)
        logger(tt_interface,tt_case,'用例参数不正确')
        return False
def test_run(data_get):
    for test_list in data_get:
        if test_list != '':
            res_page(test_list)
        else:
            continue



